<?php
$conf = new DOMDocument(); 
$conf->load( 'fields_conf.xml' ); 

$xmlDoc = new DOMDocument();

$application = $_GET['app'] ;
$year = $_GET['year'] ;
$month = $_GET['month'] ;
$day = $_GET['day'] ;
$field = $_GET['field'] ;
$correlator = $_GET['correlator'] ;

if(empty($year) || ($year == 'ALL')) 
{ 
	$year=".*";
} 
 
if(empty($month) || ($month == 'ALL')) 
{ 
	$month=".*";
}

if(empty($day)) 
{ 
	$day=".*";
}

if(empty($correlator)) 
{ 
	$correlator="off";
}

 
$event_path="/var/www/FIEM/norm_log/";
$correlated_event="/var/www/FIEM/correlator/matched_log";

$field_conf = $xmlDoc->appendChild($xmlDoc->createElement("field")); 
$apps = $conf->getElementsByTagName( "app" );
foreach( $apps as $app ) 
{
	$app_name = $app->getElementsByTagName( "name" )->item(0)->nodeValue; 
	if( $app_name == $application  )
	{
		$indexCmp = $app->getElementsByTagName( "indexCmp" )->item(0)->nodeValue;
		for ($i = 0; $i < $indexCmp; $i++) {
			$event_path = $event_path . "*/";
		} 
		$event_path = $event_path . "event.log";
		
		$xml_fields = $app->getElementsByTagName( "field" );
	 
		foreach( $xml_fields as $xml_field ) 
		{
			$field_name = $xml_field->getElementsByTagName( "name" )->item(0);
			if( $field_name->nodeValue == $field  )
			{
				$field_values = $xml_field->getElementsByTagName( "values" )->item(0)->nodeValue;
				$values = explode("|", $field_values);  
				foreach( $values as $value ) 
				{  
					$xml_field_name = $field_conf->appendChild($xmlDoc->createElement("value"));			         
					$xml_field_name->appendChild($xmlDoc->createElement("name", $value));
					if( $correlator == "on") 
						$commande= 'sudo -u www-data bash -c "cat '.$correlated_event.' | grep '.$value." | grep '".$month.'\\ \\ '.$day.'\\ .*:.*:.* '.$year."'".' | wc -l " ' ;
					else
						$commande= 'sudo -u www-data bash -c "locate -d /var/www/FIEM/fiem.db '.$event_path.' | xargs cat | grep '.$value." | grep '".$month.'\\ \\ '.$day.'\\ .*:.*:.* '.$year."'".' | wc -l" '; 
					unset($res);
					exec($commande, $res);
					$xml_field_name->appendChild($xmlDoc->createElement("occ", $res[0])); 
				}
			}
		}	 
	} 
}
header("Content-Type: text/xml");
$xmlDoc->formatOutput = true;
echo $xmlDoc->saveXML(); 
?>
